<template>
  <div>
    <el-card class="box-1">
      <div slot="header"><span>{{ title }}</span></div>
      <el-form ref="form" :model="form" :rules="formRules" label-width="160px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="form.realname"/>
        </el-form-item>
        <el-form-item label="头像">
          <ws-upload-single-img v-model="form['avatar']"
                                :path="form['avatar']?(form['avatar'].indexOf('https://')<0?(ImageUrl+form['avatar']):form['avatar']):''"/>
        </el-form-item>
        <el-form-item label="公司">
          <div>
            <el-input v-for="(companyItem, companyIndex) in form.company" v-model="form['company'][companyIndex]"
                      :key="companyIndex" placeholder="请输入公司名称">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('company', companyItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('company')">新增公司名</el-button>
          </div>
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="form.position"/>
        </el-form-item>
        <el-form-item label="客户手机" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入主要手机号码"/>
        </el-form-item>
        <el-form-item label="其他手机">
          <div>
            <el-input v-for="(mobileItem, mobileIndex) in form.spare_mobile" v-model="form['spare_mobile'][mobileIndex]"
                      :key="mobileIndex" placeholder="请输入其他联系手机号码">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('spare_mobile', mobileItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('spare_mobile')">新增手机号
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="座机">
          <div>
            <el-input v-for="(telephoneItem, telephoneIndex) in form.telephone"
                      v-model="form['telephone'][telephoneIndex]" :key="telephoneIndex" placeholder="请输入座机">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('telephone', telephoneItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('telephone')">新增座机</el-button>
          </div>
        </el-form-item>
        <el-form-item label="腾讯云ID">
          <div>
            <el-input v-for="(qqItem, qqIndex) in form.qq" v-model="form['qq'][qqIndex]" :key="qqIndex"
                      placeholder="请输入腾讯云ID">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('qq', qqItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('qq')">新增腾讯云ID</el-button>
          </div>
        </el-form-item>
        <el-form-item label="微信">
          <div>
            <el-input v-for="(wechatItem, wechatIndex) in form.wechat" v-model="form['wechat'][wechatIndex]"
                      :key="wechatIndex" placeholder="请输入微信号">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('wechat', wechatItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('wechat')">新增微信</el-button>
          </div>
        </el-form-item>
        <el-form-item label="QQ">
          <div>
            <el-input v-for="(tencentIdItem, tencentIdIndex) in form.tencent_id"
                      v-model="form['tencent_id'][tencentIdIndex]" :key="tencentIdIndex" placeholder="请输入QQ">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('tencent_id', tencentIdItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('tencent_id')">新增QQ号
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="邮箱">
          <div>
            <el-input v-for="(emailItem, emailIndex) in form.email" v-model="form['email'][emailIndex]"
                      :key="emailIndex"
                      placeholder="请输入邮箱">
              <el-button slot="append" icon="el-icon-delete" @click.prevent="removeItem('email', emailItem)"/>
            </el-input>
            <el-button type="info" plain style="margin-top: 5px;" @click.prevent="addItem('email')">新增邮箱</el-button>
          </div>
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="form.level" :disabled="!queryMatch(203)" placeholder="请选择所属等级">
            <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择所属类型">
            <el-option :value="0" label="个人"/>
            <el-option :value="1" label="企业"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源">
          <el-select v-model="form.source" placeholder="请选择客户来源">
            <el-option v-for="item in sourceList" :key="item.id" :label="item.source_name" :value="item.source_name" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-input v-model="form.create_time" :disabled="true"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"/>
        </el-form-item>
        <el-form-item label="密码确认" prop="confirmPass">
          <el-input v-model="form.confirmPass" type="password"/>
        </el-form-item>
        <el-form-item :label="form.type===0?'身份证姓名':'企业名称'">
          <el-input v-model="form.certify_name" />
        </el-form-item>
        <el-form-item :label="form.type===0?'身份证号码':'营业执照号'">
          <el-input v-model="form.certify_no" />
        </el-form-item>
        <el-form-item v-show="form.type===0" label="身份证正面">
          <ws-upload-single-img v-model="form['idcard_front_side']" :path="form['idcard_front_side']?ImageUrl+form['idcard_front_side']:''"/>
        </el-form-item>
        <el-form-item v-show="form.type===0" label="身份证反面">
          <ws-upload-single-img v-model="form['idcard_back_side']" :path="form['idcard_back_side']?ImageUrl+form['idcard_back_side']:''"/>
        </el-form-item>
        <el-form-item v-show="form.type===1" label="营业执照照片">
          <ws-upload-single-img v-model="form['enterprise_pic']" :path="form['enterprise_pic']?ImageUrl+form['enterprise_pic']:''"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" type="textarea" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1" >激活</el-radio>
            <el-radio :label="0">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="text-align:center">
          <el-button type="primary" @click="submitForm('form')">{{ id?'保存':'立即创建' }}</el-button>
          <el-button type="primary" @click="$router.back(-1)">取消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (this.title !== '编辑用户' && value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (this.form.password !== '') {
        // console.log(value);
        if (value === '' || value === null) {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.form.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    return {
      title: '',
      // ImageUrl: this.$store.getters.serverUrl,
      ImageUrl: '',

      levelList: [], // 等级列表
      sourceList: [], // 来源列表

      form: {
        name: '',
        sex: '男',
        mobile: '',
        spare_mobile: [''],
        telephone: [''],
        email: [''],
        position: '',
        company: [''],
        wechat: [''],
        qq: [''],
        tencent_id: [''],
        realname: '',
        type: '',
        avatar: '',
        level: '',
        source: '',
        project: '',
        remarks: '',
        certify_name: '',
        certify_no: '',
        create_time: '',
        idcard_front_side: '',
        idcard_back_side: '',
        enterprise_pic: '',
        password: '',
        confirmPass: '',
        status: 1
      },
      formRules: {
        name: [{ required: true, message: '请输入客户名', trigger: 'change' }],
        realname: [{ required: true, message: '请输入客户真实姓名', trigger: 'change' }],
        mobile: [{ required: true, message: '请填写手机号码', trigger: 'change' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'change' }],
        type: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
        level: [{ required: true, message: '请选择客户等级', trigger: 'change' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        confirmPass: [{ validator: validatePass2, trigger: 'blur' }]
      }
    }
  },
  watch: {
  },
  created() {
    this.title = this.$route.query.title;
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.getUserInfo(this.$route.query.id);
    }
    this.getLevelList();
    this.getSourceList();
  },
  methods: {
    /**
     *  获取用户信息
     *  接口:'member/detail/{id}'
     */
    getUserInfo(id) {
      const url = 'member/detail/' + id;
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.form = res.data
        this.form.spare_mobile = res.data.spare_mobile ? res.data.spare_mobile.split(',') : [''];
        this.form.qq = res.data.qq ? res.data.qq.split(',') : [''];
        this.form.wechat = res.data.wechat ? res.data.wechat.split(',') : [''];
        this.form.email = res.data.email ? res.data.email.split(',') : ['']
        this.form.company = res.data.company ? res.data.company.split(',') : [''];
        this.form.telephone = res.data.telephone ? res.data.telephone.split(',') : [''];
        this.form.tencent_id = res.data.tencent_id ? res.data.tencent_id.split(',') : [''];
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      });
    },

    // 动态删除项
    removeItem(paramsName, item) {
      const index = this.form[paramsName].indexOf(item)
      if (index !== -1) {
        this.form[paramsName].splice(index, 1)
      }
    },
    // 动态增加项
    addItem(paramsName) {
      this.form[paramsName].push('')
    },

    /**
     *  获取等级列表
     *  接口:'member/level-list'
     */
    getLevelList() {
      const url = 'member/level-list';
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.levelList = res.data;
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      });
    },

    /**
     *  获取等级列表
     *  接口:'member/source-list'
     */
    getSourceList() {
      const url = 'member/source-list';
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.sourceList = res.data;
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      });
    },

    /**
     * 表单提交
     * 添加客户
     */
    submitForm(formName) {
      // console.log(this.form);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.form;
          data.spare_mobile && (data.spare_mobile = data.spare_mobile.join(','))
          data.qq && (data.qq = data.qq.join(','))
          data.wechat && (data.wechat = data.wechat.join(','))
          data.company && (data.company = data.company.join(','))
          data.telephone && (data.telephone = data.telephone.join(','))
          data.email && (data.email = data.email.join(','))
          data.tencent_id && (data.tencent_id = data.tencent_id.join(','))
          const url = this.id ? 'member/edit/' + this.id : 'member/create';
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg);
            this.$router.back(-1);
          }).catch((err) => {
            this.$message.error(err.msg);
          })
        } else {
          this.$message.error('提交失败,请检查必填项');
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../styles/index.scss';
.box-1 {
  max-width: 1000px;
  margin: 0 auto;
  > div span {
    font-size: 18px;
    font-weight: 600;
    padding: 0 10px;
  }
  .el-form {
    max-width: 900px;
    .title {
      font-weight: 600;
    }
    .remark {
      font-size: 13px;
      color: $textGray;
    }
    > div >.el-button {
      @extend .bg-green;
      width: 20%;
      min-width: 160px;
    }
    >.el-button {
      @extend .bg-green;
      width: 20%;
      min-width: 160px;
    }
  }
}

.el-checkbox {
  margin-right: 30px;
}
.el-checkbox + .el-checkbox {
  margin-left: 0;
  margin-right: 30px;
}
</style>
